import {Injectable} from "@nestjs/common";
import {CreateSysDictDto} from "./dto/create-sys-dict.dto";
import {UpdateSysDictDto} from "./dto/update-sys-dict.dto";
import {SysDict} from "@/modules/sys-dict/entities/sys-dict.entity";
import {InjectRepository} from "@nestjs/typeorm";
import {Like, Not, Repository} from "typeorm";
import {ResultData} from "@/common/utils/result";
import {instanceToPlain} from "class-transformer";
import {FindListSysDictDto} from "@/modules/sys-dict/dto/find-list-sys-dict.dto";

@Injectable()
export class SysDictService {
	constructor(
		@InjectRepository(SysDict)
		private readonly sysDictRepository: Repository<SysDict>
	) {
	}
	
	async create(createSysDictDto: CreateSysDictDto) {
		console.log("createSysDictDto", createSysDictDto);
		return ResultData.ok(await this.sysDictRepository.save(createSysDictDto));
	}
	
	async findAll(findAllDto: FindListSysDictDto) {
		const {page, size, parentId, code, name} = findAllDto;
		const take = size || 15;
		const skip = ((page || 1) - 1) * take;
		const where = {
			...(parentId ? {parentId} : null),
			...(code ? {code} : null),
			...(name ? {name: Like(`%${name}%`)} : null)
		};
		return ResultData.rowOk(instanceToPlain(await this.sysDictRepository.findAndCount({
			order: {
				id: "DESC"
			},
			where,
			skip,
			take
		})));
	}
	
	async findDictByCode({code}) {
		return ResultData.ok(instanceToPlain(await this.sysDictRepository.find({
			where: {
				code,
				parentId: Not(-1),
			},
			select: ['dictKey', 'dictValue', 'id']
		})));
	}
	
	findOne(id: number) {
		return `This action returns a #${id} sysDict`;
	}
	
	async update(id: number, updateSysDictDto: UpdateSysDictDto) {
		console.log("updateSysDictDto", updateSysDictDto);
		return ResultData.ok(await this.sysDictRepository.update(id, updateSysDictDto));
	}
	
	remove(id: number) {
		return `This action removes a #${id} sysDict`;
	}
}
